define(['zepto', 'butterfly/view','../../bsl',
    'text!./proximity.html'
], function($, View, bsl, proximity) {
    var me = null;

    var view = View.extend({
        events: {
            "tap #getProximity":"getProximity",
            "tap #watchProximity":"watchProximity",
            "tap #watchStop":"watchStop",
            "tap #back":"back",
             "tap #openDoc":"openDoc",
        },
        render: function() {
            me = this;
        },

        onShow: function() {
            document.addEventListener( "plusready", function(){
            //watchProximity();
            ws=bsl.webview.currentWebview();
            // 页面隐藏时自动停止监听
            ws.addEventListener('hide',function(){
                watchStop();
            },false);
        }, false );// 绑定自定义事件 滑动切换日历等           


        },
        ws:null,
        
        getProximity:function() {
            console.info( "获取设备当前距离传感器信息" );
            bsl.proximity.getCurrentProximity( function ( d ) {
                console.info( "距离为：" + d );
            }, function ( e ) {
                console.info( "获取失败:" + e.message );
            } );
        },
        id:null,
        bright:null,
        watchProximity:function() {
            if (me.id) {
                return;
            }
            console.info( "监听设备距离传感器信息" );
            bright = bsl.screen.getBrightness();
            me.id = bsl.proximity.watchProximity( function ( d ) {
                console.info( "距离变化："+d );
                bsl.screen.setBrightness( (d<1)?0.01:bright );
            }, function ( e ) {
                bsl.proximity.clearWatch( id );
                me.id = null;
                console.info( "监听失败:" + e.message );
            } );
        },
        watchStop:function() {
            if (me.id) {
                console.info( "停止监听设备距离传感器信息" );
                bsl.proximity.clearWatch( id );
                me.id = null;
            } else {
                console.info( "没有监听设备距离传感器" );
            }
        },
        back:function(e){
            me.watchStop();
            window.history.go(-1);
        },
          openDoc:function(){
            window.butterfly.navigate('com.no5.cordovademo/doc/proximity', {
                trigger: true
            });
        }
    });
    return view;
});
